package logic

import (
	"context"
	"fmt"
	"taobao/model"

	"taobao/taobaorpc/internal/svc"
	"taobao/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *taobaorpc.ProductAddRequest) (*taobaorpc.ProductAddResponse, error) {
	// todo: add your logic here and delete this line
	var product model.Product
	err := product.FindProduct(model.DB, in.Name)
	if err != nil {
		return nil, err
	}
	if product.ID != 0 {
		return nil, fmt.Errorf("该商品已添加")
	}
	product = model.Product{
		Name:   in.Name,
		Price:  float64(in.Price),
		Stock:  in.Stock,
		UserId: int(in.UserId),
	}
	err = product.CreateProduct(model.DB)
	if err != nil {
		return nil, err
	}
	return &taobaorpc.ProductAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
